const { db, command, cloud } = require(':share/webServer')
const useMidware = require(':utils/useMidware')
const checkJson = require(':utils/checkJson')

async function checkData(ctx, next)
{
    let { slot_num } = ctx.request.body
    const scheam = {
        type: 'object',
        properties: {
            slot_num: { type: 'number' },
            release_prize_at: { type: 'number' },
            release_prize_end_at: { type: 'number' },
            prize_ids: { type: 'array', minItems: slot_num, maxItems: slot_num },
            prize_probability: { type: 'array', minItems: slot_num, maxItems: slot_num },
            release_prize_probability: { type: 'array', minItems: slot_num, maxItems: slot_num }
        },
        required: ['slot_num', 'prize_ids', 'prize_probability', 'release_prize_probability', 'release_prize_at', 'release_prize_end_at']
    }
    checkJson(ctx.request.body, scheam)
    await next()
}

async function newRoulette(ctx, next)
{
    let { prize_ids } = ctx.request.body

    let rsp
    let prizes = []
    for (prize_id of prize_ids)
    {
        rsp = await db.collection('Prizes').where({
            prize_id
        }).get()
        prizes.push(rsp.data[0])
    }

    rsp = await db.collection('Roulettes_info').where({
        name: 'max_roulette_id'
    }).get()
    let max_prize_id = rsp.data[0].value
    rsp = await db.collection('Roulettes').add({
        roulette_id: max_prize_id,
        ...ctx.request.body,
        prizes
    })

    await db.collection('Roulettes_info').where({
        name: 'max_roulette_id'
    }).update({
        value: command.inc(1)
    })
    await db.collection('Roulettes_info').where({
        name: 'roulette_num'
    }).update({
        value: command.inc(1)
    })
    await next()
}

useMidware.post('/modules/adminPage/manageRoulette/newRoulette', checkData)
useMidware.post('/modules/adminPage/manageRoulette/newRoulette', newRoulette)